﻿package com.sgcc.nfc.lock.presentation.auth

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.sgcc.nfc.lock.core.network.NetworkResult
import com.sgcc.nfc.lock.domain.usecase.GetProfileUseCase
import com.sgcc.nfc.lock.domain.usecase.LoginUseCase
import com.sgcc.nfc.lock.presentation.auth.model.LoginUiState
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import kotlinx.coroutines.launch

@HiltViewModel
class LoginViewModel @Inject constructor(
    private val loginUseCase: LoginUseCase,
    private val getProfileUseCase: GetProfileUseCase
) : ViewModel() {

    private val _state = MutableLiveData(LoginUiState())
    val state: LiveData<LoginUiState> = _state

    init {
        checkSession()
    }

    private fun checkSession() {
        viewModelScope.launch {
            when (val result = getProfileUseCase()) {
                is NetworkResult.Success -> _state.value = LoginUiState(isSuccess = true)
                else -> {}
            }
        }
    }

    fun login(username: String, password: String) {
        if (username.isBlank() || password.isBlank()) {
            _state.value = LoginUiState(errorMessage = "请输入用户名和密码")
            return
        }
        viewModelScope.launch {
            _state.value = LoginUiState(isLoading = true)
            when (val result = loginUseCase(username, password)) {
                is NetworkResult.Success -> {
                    _state.value = LoginUiState(isSuccess = true)
                }
                is NetworkResult.Error -> {
                    _state.value = LoginUiState(errorMessage = result.message ?: "登录失败")
                }
                NetworkResult.Loading -> {
                    _state.value = LoginUiState(isLoading = true)
                }
            }
        }
    }
}


